package com.open.capacity.user.controller;

import com.open.capacity.annotation.log.LogAnnotation;
import com.open.capacity.commons.Result;
import com.open.capacity.user.model.SysPermission;
import com.open.capacity.user.service.SysPermissionService;
import com.open.capacity.user.vo.SysPermissionVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;


/**
 * @author 作者 ftquan E-mail: 464725602@qq.com
 * @version 创建时间：2017年11月12日 上午22:57:51
 *          权限管理
 */
@RestController
@Api(tags = "权限模块api")
public class SysPermissionController {

    private static Logger logger = LoggerFactory.getLogger(SysPermissionController.class);


    @Autowired
    private SysPermissionService authorizeService;


    /**
     * 查询功能授权
     *
     * @param objectId
     * @return
     */
    @PreAuthorize("hasAuthority('permission:get/permissions')")
    @ApiOperation(value = "查询功能授权")
    @GetMapping("/permissions/findByObject")
    public Result<SysPermissionVo> findPermissions(String objectType, String objectId) {
        SysPermissionVo vo = new SysPermissionVo();
        List<SysPermission> list = authorizeService.findByObject(objectType, objectId);
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(r -> {
                vo.setItemType(r.getItemType());
                if (r.getItemType().equals(9)) {
                    if (vo.getItemIds() == null) {
                        vo.setItemIds(new ArrayList<>());
                    }
                    if (!vo.getItemIds().contains(r.getItemId())) {
                        vo.getItemIds().add(r.getItemId());
                    }
                }
            });
        }

        return Result.succeed(vo);
    }


    /**
     * 功能授权新增或者更新
     *
     * @param sysAuthorize
     * @return
     */
    @PreAuthorize("hasAnyAuthority('permission:post/permissions','permission:put/permissions')")
    @ApiOperation(value = "保存功能授权")
    @PostMapping("/permissions/saveOrUpdate")

    public Result saveOrUpdate(@RequestBody SysPermissionVo sysAuthorize) {
        return authorizeService.saveOrUpdate(sysAuthorize);
    }
}
